import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, HddOutlined, LoadingOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons'
import { useRequest } from '@umijs/hooks'
import { Button, Card, Drawer, Form, Input, message, Modal, Popover, Select, Table, Tag, TreeSelect } from 'antd'
import { Store } from 'rc-field-form/lib/interface'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import TableToolbar from '../../../components/TableSetting/TableToolbar'
import { fetchRequest } from '../../../utils/Request'
import { url } from '../../../utils/url'
import '../index.css'
import RecordInStudentCard from "./RecordInStudentCard";

interface Detail {
    visible: boolean,
    content: any
}

//请求参数
interface tableRequestParam {
    "whiteCardCode": null | undefined | string,
    "imeiCode": null | undefined | string,
    "cardType": null | undefined | string,
    "batchNumber": null | undefined | string,
    "index":number,
    "num":number
}

interface CheckParams {
    "Id": string
}

export default function StudentCardManageTable() {

    const { Option } = Select;

    const columns = [
        {
            title: "白卡号",
            dataIndex: "whiteCardCode",
            key: 'whiteCardCode'
        },{
            title: "IMEI",
            dataIndex: "imeiCode",
            key: 'imeiCode'
        },{
            title: "卡类型",
            dataIndex: "cardType",
            key: 'cardType',
            render: (text: number) => {
                return text===1?"智能学生证":text===2?"普通白卡":"未知卡类型"
            }
        },{
            title: "批次号",
            dataIndex: "batchNumber",
            key: 'batchNumber'
        },{
            title: "录入时间",
            dataIndex: "batchDate",
            key: 'batchDate'
        }, {
            title: "操作",
            render: (record: any) => <span onClick={e => e.stopPropagation()}>
                <Tag className="tags-hover deletes" color="#f50"
                     onClick={e => {
                         // deleteStudentCard.run({"id": record.id})
                         // checkAccess.run({ Id:record.Id})
                         showDeleteConfirm(record)
                     }} icon={ <DeleteOutlined />}>删除</Tag>

               {/*<Tag className="tags-hover" color="#00BFFF"*/}
               {/*     onClick={() => seteditVisible({ visible: true, content: record })}*/}
               {/*     icon={ <EditOutlined />}>修改</Tag>*/}

        </span>
        }]

    const [tableRequestParam, setTableRequestParam] = useState<tableRequestParam>({ whiteCardCode: "", imeiCode: "", cardType: "", batchNumber: "", index:1, num:10 });

    const [tableData, setTableData] = useState<any>([]);

    const [addVisible, setaddVisible] = useState<boolean>(false)

    const [columnsKey, setcolumnsKey] = useState<any[]>([])

    const [realColumns, setrealColumns] = useState<any[]>([])

    const [editVisible, seteditVisible] = useState<{ visible: boolean, content: any }>({ visible: false, content: null })

    const [form] = Form.useForm();


    function showDeleteConfirm(info: any) {
        Modal.confirm({
            title: '确定删除?',
            icon: <ExclamationCircleOutlined />,
            content: info.message,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                deleteStudentCard.run({
                    "id": info.id
                })
            },
        });
    }

    const deleteStudentCard = useRequest(deleteStudentCardRequest, {
        loadingDelay: 200,
        manual: true
    });

    //删除的请求函数
    async function deleteStudentCardRequest(params: any) {
        // console.log(params)
        try {
            const json = await fetchRequest(url.DELETE_STUDENT_CARD, params);
            if (json.success) {
                message.destroy();
                message.success("删除成功!")
                if (tableData.count > tableRequestParam.num && tableData.count - 1 === tableRequestParam.index * tableRequestParam.num) {
                    setTableRequestParam({ ...tableRequestParam, index: tableRequestParam.index - 1 })
                } else {
                    getStudentCard.run(tableRequestParam)
                }
            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)

        }
    }

    //点击搜索按钮
    function handleFinish(values: any) {
        // console.log("搜索参数")
        // console.log(values)
        setTableRequestParam({
            whiteCardCode: typeof values.whiteCardCode === "undefined" ? "" : values.whiteCardCode,
            imeiCode: typeof values.imeiCode === "undefined" ? "" : values.imeiCode,
            cardType: typeof values.cardType === "undefined" ? "" : values.cardType,
            batchNumber: typeof values.batchNumber === "undefined" ? "" :  values.batchNumber,
            index: 1, num: 10
        })
    }

    //点击重置按钮
    function handleReset() {
        form.resetFields();
        setTableRequestParam({ whiteCardCode: "", imeiCode: "", cardType: "", batchNumber: "", index: 1, num: 10 })
    }

    //递归删除空的children
    function deleteEmpty(arr: any[]) {
        arr.map(item => {
            if (item.children.length === 0) {
                delete item.children
            } else {
                deleteEmpty(item.children)
            }
        })
    }
    
    //查询框
    const searchForm = (<Card className="search-form"> <Form form={form} layout="inline" initialValues={{ healthState: -1 }} onFinish={handleFinish} onReset={handleReset}>

        <Form.Item className="form-control-item" name="whiteCardCode" label="白卡号">
            <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item" name="imeiCode" label="IMEI">
            <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item" name="cardType" label="卡类型">
            <Select
                // style={{ width: '20%' }}
                placeholder="请选择卡类型"
                // defaultValue="1"
                // onChange={CardTypeOnChange}
            >
                <Option value="1">智能学生证</Option>
                <Option value="2">普通白卡</Option>
            </Select>
        </Form.Item>

        <Form.Item className="form-control-item" name="batchNumber" label="批次号">
            <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item"  >
            <Button key="1" type="primary" icon={<SearchOutlined />} htmlType="submit" style={{ marginRight: '8px' }}>搜索</Button>
            <Button key="2" icon={<SyncOutlined />} htmlType="reset">重置</Button>

        </Form.Item>

    </Form></Card>)



    const [detail, setDetail] = useState<Detail>({ visible: false, content: null })


    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])


    //点击行的时候
    function onRowClick(value: any) {
        // console.log(value)
        setDetail({ visible: true, content: value })
    }

    //当列设置改变的时候
    function onColumnsChange(checkedList: any[]) {
        // console.log(checkedList)
        setcolumnsKey(checkedList)
    }


    //获取门禁人员信息管理的table
    const getStudentCard = useRequest(getStudentCardRequest, {
        loadingDelay: 200,
        manual: true
    })

    //监听请求参数的变化 变化之后进行请求
    useEffect(() => {
        getStudentCard.run(tableRequestParam)
    }, [tableRequestParam])


    //递归修改item的key
    function disableSelect(arr: any[],) {
        // console.log("进入disableselect")
        arr.map(item => {
            // delete item.disabled
            item.key = item.deptID
            item.value = item.deptID
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }

    const dispatch = useDispatch();

    //异步请求的接口
    async function getStudentCardRequest(params: tableRequestParam) {
        try {
            const json = await fetchRequest(url.GET_STUDENT_CARD_LIST, params);
            if (json.success) {
                setTableData(json.data);
            } else {
                message.error(json.errorMsg)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    //点击刷新按钮
    function onRefresh() {
        getStudentCard.run(tableRequestParam)
    }

    //点击新增按钮
    function onAdd() {
        setaddVisible(true)
    }



    //新增成功
    function addSuccess() {
        message.destroy();
        message.success("新增成功!");
        setaddVisible(false);
        getStudentCard.run(tableRequestParam)
    }

    //新增成功
    function onaddSuccess() {
        message.destroy();
        message.success("修改成功!");
        seteditVisible({...editVisible,visible:false});
        getStudentCard.run(tableRequestParam)
    }


    //点击分页的时候
    function handlePageChange(page: number) {
        setTableRequestParam({
            ...tableRequestParam,
            index: page
        })
    }


    return (
        <div>
            {searchForm}
            <Card className="search-form-table">
                <TableToolbar tableName="学生证录入信息管理表" columns={columns} onColumnsChange={onColumnsChange} onRefresh={onRefresh} onAdd={onAdd} />
                <Table
                    loading={getStudentCard.loading}

                    pagination={{
                        hideOnSinglePage: true, simple: true, pageSize: 10,
                        onChange: handlePageChange,
                        total:tableData.total
                    }}
                    onRow={(record: any) => {
                        return { onClick: e => onRowClick(record) }
                    }} rowKey={(record: any) => record.id} columns={realColumns}
                    // dataSource={data}
                    dataSource={tableData.rows}
                />
            </Card>
            <Drawer width="60%" destroyOnClose visible={addVisible} title="新增学生证" onClose={() => setaddVisible(false)}>
                <RecordInStudentCard addSuccess={addSuccess} />
            </Drawer>
        </div>
    )
}
